package com.sx.core.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * Created by lihao on 2018/3/16.
 */
@Component("propertyUtils")
@Lazy(false)
public class PropertyUtils implements ApplicationContextAware, DisposableBean {
    private static final Log logger = LogFactory.getLog(PropertyUtils.class);

    private static ApplicationContext applicationContext;

    private static Environment env;



    public static String getProperty(String key) {
        return env.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {

        return env.getProperty(key, defaultValue);
    }
    public static String getPropertyUtf8(String key) {
        try {
            return new String(env.getProperty(key, "").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        return null;
    }

    public static boolean isProperty(String key,String val){
        return StringUtils.equals(getProperty(key),val);
    }

    @Override
    public void destroy() throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        PropertyUtils.applicationContext=applicationContext;
        PropertyUtils.env=applicationContext.getBean(Environment.class);
    }
}
